﻿<?php
// 家族个人节点-2016年7月23日
use Phalcon\Paginator\Adapter\Model as PaginatorModel;//分页
//use Phalcon\Mvc\Model\Transaction\Manager as TxManager;//model支持join
//use Phalcon\Mvc\Model\Query;
class NodeController extends BaseController
{
    public function indexAction()
    {
        parent::load([
			'title' =>  '族人',
            'js'    =>  'index',
            'css'   =>  'index'
		]);
        $genno = $this->request->getQuery('genno');
        //  导航
        $nav = '<a href="javascript:void(0);" url="/TeClan/Node/crtnode'.($genno? '?genno='.$genno:'').'" id="crtnodeBtn">录入成员</a>';
        if($genno) $nav .= '<span id="query_genno" genno="'.$genno.'"></span>';

        //  人物清单
        $cpage = isset($_GET['page'])? intval($_GET['page']):1;
        $nds = Node::find('gen_no="'.$genno.'"');
        $paginator = new PaginatorModel(
            array(
                "data"  => $nds,
                "limit" => 30,
                "page"  => $cpage
            )
        );
        $page = $paginator->getPaginate();
        $nlist = '';
        //foreach($nds as $obj){
        foreach($page->items as $obj){
            $nlist .= '<li nodeid="'.$obj->pers_id.'">
                <a href="javascript:void(0);" class="nameBtn">'.$obj->name.'</a>
                <span class="zibei"><a href="javascript:void(0);">'.$obj->zibei.'</a></span>
                <span class="mtime">'.$obj->mtime.'</span>
                <span class="editbtn"><a href="javascript:void(0);" class="editBtn">修改</a>
                <a href="javascript:void(0);" class="deleteBtn">删除</a></span>
            </li>';
        }
        if($nlist){
            $nlist = '<ul>
                <li class="title"><a href="JavaScript:void(0);" class="nameBtn">姓名</a><span class="zibei"><a href="JavaScript:void(0);">字辈</a></span><span class="mtime"><a href="JavaScript:void(0);">添加时间</a></span><span class="editbtn"><a href="JavaScript:void(0);">操作</a></span></li>
                '.$nlist.'</ul>';
            $url = '/TeClan/Node/index?genno='.$genno.'&page=';
            $nlist .= '<p id="nlist_page">'.$this->dec2page($page,$url).'</p>';
        }
        $this->view->setVars(array(
            'nav'       =>  $nav,
            'nodeList'  =>  $nlist
        ));
    }
    public function crtnodeAction()
    {
        //  访问合法性检测
        $genno = $this->request->getQuery('genno');
        if(empty($genno)) $genno = $this->request->getPost('gen_no');
        if(empty($genno)){
            $this->response->redirect('error/show403'); //url 跳转
            $this->view->disable();            
            return false;
        }

        parent::load([
            'js'    =>  'crtnode',
            'css'    =>  'crtnode'
        ]);
        $form = new NodeForm;

        if ($this->request->isPost()) {            
            $data = $this->request->getPost();
            $mode = $data['datamode'];            
            $id = $data['pers_id'];
            unset($data['datamode']);unset($data['pers_id']);
            if(empty($data['zibei_no'])){
                unset($data['zibei_no']);unset($data['zibei']);
            }

            if($mode == 'A'){// 新增
                $nd = new Node();
                $data['gen_no'] = $genno;
                //$this->autoCrtSerNo;
                if(!empty($data['father'])){
                    /*  //排序无效
                    $nd4Sn = Node::findFirst(array(
                        array('father' => $data['father']),
                        'order' =>  array('ser_no'=>1)
                    ));
                    */
                    $nd4Sn = Node::findFirst(array('father="'.$data['father'].'"','order'=>'ser_no desc'));
                    $data['ser_no'] = intval($nd4Sn->ser_no)+1;//自动排序
                    //~ 数据学习
                    if(empty($data['mother']) && !empty($nd4Sn->mother)) $data['mother'] = $nd4Sn->mother;
                    if(empty($data['zibei']) && !empty($nd4Sn->zibei)) $data['zibei'] = $nd4Sn->zibei;
                    if(empty($data['zibei_no']) && !empty($nd4Sn->zibei_no)) $data['zibei_no'] = $nd4Sn->zibei_no;
                    /*
                    if((!isset($data['zibei']) || empty($data['zibei'])) && !empty($nd4Sn->zibei)) $data['mother'] = $nd4Sn->zibei;
                    if((!isset($data['zibei_no']) || empty($data['zibei_no'])) && !empty($nd4Sn->zibei_no)) $data['mother'] = $nd4Sn->zibei_no;
                    */
                }else $data['ser_no'];
                //debug($data);
                //$this->flash->error('<pre>'.print_r($data,true));return false;
                $data = array_merge($data,$this->baseData());
                $ret = $nd->save($data);            
                if($ret == false){
                    foreach ($nd->getMessages() as $message) {
                        $this->flash->error($message);
                    }
                }
                $this->flash->error("数据写入成功(..)！");
                return false;  
            }elseif($mode == 'Del'){//删
                $nd = Node::findFirst('pers_id="'.$id.'"');
                if($nd->delete() == true){
                    foreach ($nd->getMessages() as $message) {
                        echo $message, "\n";
                    }
                }
                $this->flash->error("数据成功删除(××)！");
                return false;  
            }elseif($mode == 'Edit'){//改
                $nd = Node::findFirst('pers_id="'.$id.'"');
                if($nd->update($data) == true){
                    foreach ($nd->getMessages() as $message) {
                        echo $message, "\n";
                    }
                }
                $this->flash->error("数据修改成功(//)！");
                return false;  
            }                           
        }
        /*
        public boolean save ([array $data], [array $whiteList])
        $robot->save(
            $_POST,
            array(
                'name',
                'type'
            )
        );
        */

        //数据可选
        $selNode = $this->getNodeList($genno);
        $this->view->setVar('selectNode',$selNode);//可选家族人员

        $this->view->form = $form;
    }
    //  crtnode的Node数据源
    public function getNodeList($genno,$no=null)
    {
        $no = empty($no)? 1: intval($no);
        $selNode = '';
        $ndObj = Node::find(array('gen_no="'.$genno.'"','order'=>'mtime desc'));
        $paginator = new PaginatorModel(
            array(
                "data"  => $ndObj,
                "limit" => 30,
                "page"  => $no
            )
        );
        $nodes = $paginator->getPaginate();
        foreach($nodes->items as $obj){
            $selNode .= '<li><a href="javascript:void(0);" class="iptHelpler" pers="'.$obj->pers_id.'/'.$obj->sex.'" onClick="Te.pHelper(this)">'.$obj->name.'</a><span>'.$obj->zibei.'</span><span>'.$obj->mtime.'</span></li>';
        }
        if($selNode){
            $selNode = '<ul>'.$selNode.'</ul>';
            $selNode .= '<p>';
            $cur = $nodes->current;
            $all = $nodes->total_pages;
            $selNode .=                
                ($cur>2? '<a href="javascript:void(0)" onClick="Te.pageTo(\'1\')"> << </a>':'')
                .($cur>1? '<a href="javascript:void(0)" onClick="Te.pageTo(\''.$nodes->before.'\')"> < </a>':'')
                .'<a href="javascript:void(0);">'.$cur.'</a> / <a href="javascript:void(0);">'.$all.'</a>'
                .($nodes->next>$cur? '<a href="javascript:void(0)" onClick="Te.pageTo(\''.$nodes->next.'\')"> > </a>':'')
                .($all>$cur+1? '<a href="javascript:void(0)" onClick="Te.pageTo(\''.$nodes->last.'\')"> >> </a>':'')                
            ;
            $selNode .= '</p>';
        }
        return $selNode;
    }
    // 利用js库绘制家谱图
    public function drawnAction()
    {
        //  访问合法性检测
        $id = $this->request->getQuery('pers');
        if(empty($id)){
            $this->response->redirect('error/show403'); //url 跳转
            $this->view->disable();            
            return false;
        }
        $models = $this->drawnscript($id);
        if(count($models)>0) $script = '<script> var loadModel =['.implode(',',$models).'];</script>';
        parent::load([
            'js_self'   =>  'go',     //自定义js/下目录
            'js'        =>  'drawn',
            'script'    =>  $script
        ]);
        $this->view->setVars(array(
            'pers'  => $id
        ));
    }
    //  返回作图数据库的对象
    public function drawnscript($id,$ischild=false)
    {
        $tmp = [];
        $nd = Node::findFirst('pers_id="'.$id.'"');
        if(!$ischild) $tmp[] = '{"key":"'.$id.'","name": "'.$nd->name.'"}';
        $map = array('order' => 'ser_no asc');
        $map[] = $nd->sex == 'M'? 'father="'.$id.'"':'mother="'.$id.'"';
        $chnds = Node::find($map);	
        foreach($chnds as $n){
            $tmp[] = '{key:"'.$n->pers_id.'","parent":"'.$id.'","name": "'.$n->name.'"}';
            $tmp2 = $this->drawnscript($n->pers_id,true);
            if(count($tmp2)>0) $tmp = array_merge($tmp,$tmp2);
        }
        return $tmp;
    }
    /****---------ajax响应-----------*/
    public function ajaxAction()
    {
        $data = ajax();
        $ret = '';
        $i = isset($data['i1'])? $data['i1']:'';
        if($i == 'getNode'){
            $ret = $this->getNodeList($data['genno'],$data['no']);
        }elseif($i == 'cn_nameburl'){   //名字检测/字辈自动匹配
            $ret = $data['name'];
            $ns = Node::find(array(
                'name="'.$data['name'].'"',
                'gen_no="'.$data['gen_no'].'"'
            ));
            $name = '';
            if(count($ns)>0){
                foreach($ns as $v){
                    $pName = '未查到';
                    if($v->father){
                        $pNode = Node::findFirst('pers_id="'.$v->father.'"');
                        $pName = $pNode->name;
                    }
                    $name .= '<a href="javascript:void(0);" title="'.$pName.'">'.$v->name.'</a>';
                }
                $name = $name? base64_encode($name):'""';
            }
            $sel = '';
            if(isset($data['zibei_no'])){
                $sel = $this->getPZibei($data['zibei_no']);
                if(empty($sel)) $sel = '""';
            }
            $ret = json_encode(array(
                'name' => $name,
                'sel'  => $sel
            ));
        }elseif($i == 'zibeiAuto'){//   字辈自动匹配父亲
            $ret = $this->getPZibei($data['zibei_no']);
        }elseif($i == 'searchName'){//  名字搜索-限定100
            $ipt = $data['name'];
            $nds = Node::find(array(
                'gen_no="'.$data['gen_no'].'" and name like "%'.$ipt.'%"',
                "limit" =>100,'order'=>'mtime desc'
            ));
            foreach($nds as $v){
                $name = str_replace($ipt,'<span style="color:red;">'.$ipt.'</span>',$v->name);
                $ret .= '<li><a href="javascript:void(0);" class="iptHelpler" pers="'.$v->pers_id.'/'.$v->sex.'" onClick="Te.pHelper(this)">'.$name.'</a><span>'.$v->zibei.'</span><span>'.$v->mtime.'</span></li>';;
            }
            if($ret) $ret = base64_encode($ret);
        }elseif($i == 'index/search_name'){//   名字搜索
            $nds = Node::find(array(
                'gen_no="'.$data['genno'].'" and name like "%'.$data['name'].'%"',
            ));
            foreach($nds as $obj){
                $ret .= '<li nodeid="'.$obj->pers_id.'">
                    <a href="javascript:void(0);" class="nameBtn" onClick="Te.nameInfor(this)">'.$obj->name.'</a>
                    <span class="zibei"><a href="javascript:void(0);">'.$obj->zibei.'</a></span>
                    <span class="mtime">'.$obj->mtime.'</span>
                    <span class="editbtn"><a href="javascript:void(0);" onClick="Te.editBtn(this)" class="editBtn">修改</a>
                    <a href="javascript:void(0);" onClick="Te.deleteBtn(this)" class="deleteBtn">删除</a></span>
                </li>';
            }
            if($ret){
                $ret = '<ul>
                    <li class="title"><a href="JavaScript:void(0);" class="nameBtn">姓名</a><span class="zibei"><a href="JavaScript:void(0);">字辈</a></span><span class="mtime"><a href="JavaScript:void(0);">添加时间</a></span><span class="editbtn"><a href="JavaScript:void(0);">操作</a></span></li>
                    '.$ret.'</ul>';
                $url = '/TeClan/Node/index?genno='.$genno.'&page=';
                //$nlist .= '<p id="nlist_page">'.$this->dec2page($page,$url).'</p>';
            }
        }elseif($i == 'drawn/init'){
            header('content-type:text/plain;charset=utf-8;');
            $ret = json_decode('
                [ 
                    {"key": "1", "parent": "1", "name": "Alonzo",     "source": "cat5.png" },
                    { "key": "2", "parent": "1", "name": "Munkustrap", "source": "cat6.png" }
                ]
            ',true);
            $ret = json_encode($ret);
            /*
            $ret = '
                [ 
                    { key: "1",              name: "Don Meow",   source: "cat1.png" },
                    { key: "2", parent: "1", name: "Demeter",    source: "cat2.png" },
                    { key: "3", parent: "1", name: "Copricat",   source: "cat3.png" },
                    { key: "4", parent: "3", name: "Jellylorum", source: "cat4.png" },
                    { key: "5", parent: "3", name: "Alonzo",     source: "cat5.png" },
                    { key: "6", parent: "2", name: "Munkustrap", source: "cat6.png" }
                ]
            ';*/
        }
        die($ret);
    }
    //  获取父辈名称
    public function getPZibei($zibei)
    {
        $sel = '';
        $pZibei = Zibei::findFirst('zibei_no="'.$zibei.'"');
        $zbNo = $pZibei->parent_no;
        if($zbNo){
            $selNode = Node::find(array('zibei_no="'.$zbNo.'" and sex="M"',"limit" =>100,'order'=>'mtime desc'));// 性别限制无效
            
            foreach($selNode as $v){
                $sel .= '<li><a href="javascript:void(0);" class="iptHelpler" pers="'.$v->pers_id.'/'.$v->sex.'" onClick="Te.pHelper(this)">'.$v->name.'</a><span>'.$v->zibei.'</span><span>'.$v->mtime.'</span></li>';
            }
        }                
        if($sel) $sel = base64_encode('<ul><li><a href="JavaScript:Te.pageTo(\'1\')">返回</a></li>'.$sel.'</ul>');
        return $sel;
    }
}
?>